<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/imports')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormet(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hFields">
        <!-- 子组件 -->
        <emDialog ref="diaRef" @close="showDialog=false" @success="hsuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import emDialog from './empDialog.vue'
import EmployeesEnum from '@/components/constant/employees'
// 枚举遍历筛选保存新对象
const hireType = {}
// 循环取出键值对 - 枚举转换方法2
EmployeesEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
// 请求参数 - 获取员工列表 - 删除员工
import { getEmployees, delEmployee } from '@/api/employees'
export default {
  name: 'Employees',
  components: {
    emDialog
  },
  data() {
    return {
      showDialog: false, // 弹层显示隐藏
      page: 1, // 默认页码
      size: 5, // 每页条数
      list: [], // 员工列表储存
      total: 0 // 数量
    }
  },
  created() {
    this.loagEmployees()
  },
  methods: {
    // 清空表单
    hFields() {
      this.$refs.diaRef.resetForm()
    },
    // 导入功能的关键代码
    formatDate(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const obj = list[0]
      if (!obj) return
      const header = Object.keys(obj).map(enkey => {
        // console.log(map[enkey])
        return map[enkey]
      })
      const data = list.map(item => {
        // console.log(item)
        // 枚举转换 - 保存变量中
        const key = item.formOfEmployment
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })
      return { header: header, data: data }
    },
    // 思路
    // - 1  发送请求获取数据 - 导出
    async handleDownload() {
      try {
        const res = await getEmployees(this.page, this.size)
        const { header, data } = this.formatDate(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
        // excel 指的是模块对象，可以使用excel调用 Export2Excel文件中的函数或者使用Export2Excel文件中的变量
          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename, // 文件名
            autoWidth: this.autoWidth, // 自动适配宽度
            bookType: this.bookType // 文件的类型
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除员工
    async hDel(id) {
      try {
        await delEmployee(id)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loagEmployees()
      } catch (error) {
        console.log(error)
      }
    },
    // 新增
    hsuccess() {
      // 新增完成页面跳转
      this.total++
      const max = Math.ceil(this.total / this.size)
      this.page = max
      this.loagEmployees()
      this.showDialog = false
    },
    // 分页器
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loagEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loagEmployees()
    },
    // 获取员工列表数据
    async loagEmployees() {
      try {
        const { data: res } = await getEmployees(this.page, this.size)
        this.list = res.data.rows // 员工列表储存
        this.total = res.data.total
        // console.log('获取员工列表', res)
      } catch (error) {
        console.log(error)
      }
    },
    // 枚举
    formOfEmploymentFormet(data) {
      return hireType[data] || '未知错误'
    }

  }
}
</script>
